import gtk
import time
import server
import pynotify
import threading

global _list

_list = None

class ListThread(threading.Thread):
    '''This class manages the contact list. It updates it every 10
    seconds'''
    def __init__(self):
        self.stopevent = threading.Event()
        threading.Thread.__init__(self)
        
    def run(self): # Update contact list 
        while not self.stopevent.isSet():
            time.sleep(10)
            
            update()

    def stop(self):
        self.stopevent.set()


def append(entry):
    if _list == None: return
    
    return _list.append(entry)

def clear():
    if _list == None: return
    
    return _list.clear()

def populate():
    if _list == None: return
    
    _list.clear()
    
    list, err = server.get_contact_list(server.username)

    img_on = gtk.gdk.pixbuf_new_from_file("pixbuf/online.svg")
    img_off = gtk.gdk.pixbuf_new_from_file("pixbuf/offline.svg")

    for item in list:
        
        if item[1] == "1": entry = (item[0], item[2], 1, img_on, False)
        else: entry = (item[0], item[2], 0, img_off, False)
        
        _list.append(entry)

def update():
    if _list == None: return

    list, err = server.get_contact_list(server.username)
    if list == None:
        print err
        return

    img_on = gtk.gdk.pixbuf_new_from_file("pixbuf/online.svg")
    img_off = gtk.gdk.pixbuf_new_from_file("pixbuf/offline.svg")
    
    iter = _list.get_iter_first()
    if iter == None: return
    for item in list:
        status = _list.get_value(iter, 2)
        if item[1] != str(status):
            n = None
            
            if status == 1:
                _list.set(iter, 2, 0, 3, img_off, 1, item[2])
                n = pynotify.Notification("DummyChat", item[0] + " is now offline.")
                img_logo = gtk.gdk.pixbuf_new_from_file("pixbuf/logout.svg")
            else:
                _list.set(iter, 2, 1, 3, img_on,  1, item[2])
                n = pynotify.Notification("DummyChat", item[0] + " is now online.")
                img_logo = gtk.gdk.pixbuf_new_from_file("pixbuf/logged.svg")
                
            n.set_icon_from_pixbuf(img_logo)
            n.show()
                
        if item[1] == "1": entry = (item[0], item[2], 1, img_on, False)
        else: entry = (item[0], item[2], 0, img_off, False)
        
        iter = _list.iter_next(iter)
